const { SensitiveWord } = require('../model/sensitiveWord');
const { success, fail } = require('../utils/response');
const { redisSet, redisGet } = require('../utils/redis');

const SENSITIVE_WORDS_KEY = 'mim-sensitive-words';

// 更新Redis中的敏感词列表
async function updateRedisWords() {
    const words = await SensitiveWord.find({ status: 0 }).lean();
    const wordMap = {};
    words.forEach(item => {
        wordMap[item.word] = item;
    });
    await redisSet(SENSITIVE_WORDS_KEY, wordMap);
}

// 创建敏感词
exports.create = async (req, res) => {
    try {
        const { word } = req.body;

        // 检查是否已存在
        const existing = await SensitiveWord.findOne({ word });
        if (existing) {
            return res.json(fail('敏感词已存在'));
        }

        const sensitiveWord = new SensitiveWord(req.body);
        await sensitiveWord.save();
        // 更新Redis
        await updateRedisWords();
        res.json(success(sensitiveWord));
    } catch (err) {
        res.json(fail(err.message));
    }
};

// 获取敏感词列表
exports.list = async (req, res) => {
    try {
        const { page = 1, limit = 10, word, status } = req.query;
        const query = {};
        const pageNum = parseInt(page);
        const limitNum = parseInt(limit);

        if (word) {
            query.word = new RegExp(word, 'i');
        } else {
            delete query.word;
        }
        if (status !== undefined) {
            query.status = parseInt(status);
        }

        // 使用Promise.all并行执行查询
        const [total, list] = await Promise.all([
            SensitiveWord.countDocuments(query).maxTimeMS(5000),
            SensitiveWord.find(query)
                .sort({ createdAt: -1 })
                .skip((pageNum - 1) * limitNum)
                .limit(limitNum)
                .maxTimeMS(5000)
                .lean()  // 转换为普通JS对象，提高性能
        ]);

        res.json(success({
            list,
            pagination: {
                total,
                page: pageNum,
                limit: limitNum
            }
        }));
    } catch (err) {
        console.error('List query error:', err);
        res.json(fail(err.message, 500));
    }
};

// 更新敏感词
exports.update = async (req, res) => {
    try {
        const { id } = req.params;
        const { word } = req.body;

        // 如果要更新word，需要检查是否与其他记录重复
        if (word) {
            const existing = await SensitiveWord.findOne({
                word,
                _id: { $ne: id }
            });
            if (existing) {
                return res.json(fail('敏感词已存在'));
            }
        }

        const sensitiveWord = await SensitiveWord.findByIdAndUpdate(
            id,
            req.body,
            { new: true }
        );

        if (!sensitiveWord) {
            return res.json(fail('敏感词不存在'));
        }

        // 更新Redis
        await updateRedisWords();
        res.json(success(sensitiveWord));
    } catch (err) {
        res.json(fail(err.message));
    }
};

// 删除敏感词
exports.delete = async (req, res) => {
    try {
        const { id } = req.params;
        const sensitiveWord = await SensitiveWord.findByIdAndDelete(id);

        if (!sensitiveWord) {
            return res.json(fail('敏感词不存在'));
        }

        // 更新Redis
        await updateRedisWords();
        res.json(success(null, '删除成功'));
    } catch (err) {
        res.json(fail(err.message));
    }
}; 